﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.WeixinService;
using Senparc.Weixin.MP.AdvancedAPIs;
using ZLCMS.Business.Util;
using ZLCMS.Commands.Member.Commands.Member;
using DotNet.Common.Command;
using Newtonsoft.Json;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace ZLCMS.Web.Wap.Member
{
    public partial class LoginWeixin : System.Web.UI.Page
    {
        protected string OAuthResultJSON { get; set; }

        protected string QrPath { get; set; }

        protected string CheckString { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (WeixinUtil.IsWeixinBroswer())
            {
                if (!string.IsNullOrEmpty((string)Session[GlobalSessionString.CurrentMemberAccount]))
                {
                    //有授权信息
                    if (!string.IsNullOrEmpty(Request["goto"]))
                    {
                        Server.Transfer(string.Format("LoginSuccess.aspx?token={0}&goto={1}&origin={2}", (string)Session[GlobalSessionString.CurrentMemberAccount], Server.UrlEncode(Request["goto"]), Server.UrlEncode(Request["origin"])));
                    }
                    else
                    {
                        Server.Transfer("/Wap/Tips/Default.aspx?t=登录成功&title=登录成功");
                    }
                }

                //包含openid信息
                if (!string.IsNullOrEmpty(Request["openid"]) || !string.IsNullOrEmpty(Request["code"]))
                {
                    ICommandResult<LoginOAuthResult> result = new LoginWeixinCommand().Execute(new LoginOAuthParameter() { Context = this.Context });
                    //登录成功
                    if (!result.Error)
                    {
                        Server.Transfer(string.Format("LoginSuccess.aspx?token={0}&goto={1}&origin={2}", result.Result.Token, Server.UrlEncode(Request["goto"]), Server.UrlEncode(Request["origin"])));
                    }
                    //需要使用snsapi_userinfo方式获取用户信息
                    else if (result.ErrorCode == "wx01")
                    {
                        string redirectUrl = ServerUtil.GetRootURI() + Context.Request.RawUrl;
                        redirectUrl = redirectUrl.Replace("code=" + Request["code"], "").Replace("state=" + Request["state"], "");
                        string url = OAuth.GetAuthorizeUrl(WeixinUtil.GetAppid("admin"), redirectUrl, "snsapi_userinfo", OAuthScope.snsapi_userinfo);
                        Response.Redirect(url);
                    }
                    //成功获取openid，但是帐号不存在
                    else if (result.ErrorCode == "0121")
                    {

                        //
                        //以下是正常流程
                        //
                        //测试模拟数据
                        //result.Result.OAuthResult.OpenId = "openid_" + DateTime.Now.Ticks;
                        //result.Result.OAuthResult.NickName = "某人";
                        //result.Result.OAuthResult.Sex = "1";
                        //result.Result.OAuthResult.PhotoUrl = "IMAGE";

                        //不跳转（询问绑定/自动创建用户）
                       // OAuthResultJSON = JsonConvert.SerializeObject(result.Result.OAuthResult);


                        //
                        //非正常流程
                        //
                        //在此自动创建帐号
                        ICommandResult<SignupAutoResult> signupAutoCommand = new SignupAutoCommand().Execute(new SignupAutoParameter() { OAuthKind = "wx", OAuthData = result.Result.OAuthResult });

                        if (signupAutoCommand.Error)
                        {
                            Response.Write(result.ErrorMsg + "【如遇到无法登录情况，请稍后再试。如仍然无法登录，请联系客服】");
                            Response.End();
                        }
                        else
                        {
                            Server.Transfer(string.Format("LoginSuccess.aspx?token={0}&goto={1}&origin={2}", signupAutoCommand.Result.Token, Server.UrlEncode(Request["goto"]), Server.UrlEncode(Request["origin"])));
                        }

                    }
                    //系统错误，中断流程！
                    else
                    {
                        Response.Write(result.ErrorMsg + "【如遇到无法登录情况，请稍后再试。如仍然无法登录，请联系客服】");
                        Response.End();
                    }
                }
                //可用网页授权获取
                else if(WeixinUtil.GetConfig("admin").OauthEnable == "1")
                {
                    //只获取openid
                    string url = OAuth.GetAuthorizeUrl(WeixinUtil.GetAppid("admin"), ServerUtil.GetRootURI() + Context.Request.RawUrl, "snsapi_base", OAuthScope.snsapi_base);
                    Response.Redirect(url);
                }
                //返回登录
                else
                {
                    Server.Transfer("login.aspx?goto=" + Server.UrlEncode(Request["goto"]));
                }
            }
            //返回登录
            else
            {
                //使用扫一扫登录
                CheckString = Guid.NewGuid().ToString("N");
                using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    session.CreateSQLQuery("INSERT into member_qrscan_info (CHECK_STRING,`STATUS`,RECORD_DATE) values(:c,'0',:d)")
                        .SetParameter("c", CheckString)
                        .SetParameter("d", DateTime.Now)
                        .ExecuteUpdate();
                }

                string url = ServerUtil.GetRootURI() + "/wap/member/weixinqrscan.aspx?ckstr=" + CheckString;



                //使用资源服务器生成二维码
                string serverUrl = ParamKit.GetValue("SystemConfig", "IMAGESERVER_URL", "");
                string appid = ParamKit.GetValue("SystemConfig", "IMAGESERVER_APPID", "");
                string appsecrect = ParamKit.GetValue("SystemConfig", "IMAGESERVER_APPSECRECT", "");


                System.Security.Cryptography.HashAlgorithm md5 = System.Security.Cryptography.MD5.Create();

                string codeUrl = url;

                string cfgStr = JsonConvert.SerializeObject(new { width = 500, height = 500, key = CheckString, data = codeUrl });

                //计算签名
                string encypStr = appid + "#" + cfgStr + "#" + appsecrect;

                string sign = System.BitConverter.ToString(md5.ComputeHash(Encoding.GetEncoding("UTF-8").GetBytes(encypStr)))
                        .Replace("-", "").ToUpper();


                string postURL = serverUrl + "/GetBarcodeImg.aspx?appid=" + appid + "&cfg=" + HttpUtility.UrlEncode(cfgStr) + "&sign=" + sign;


                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(postURL);

                var httpWebResponse = (HttpWebResponse)wr.GetResponse();
                string responseContent;
                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseContent = httpStreamReader.ReadToEnd();
                }
                JObject respObj = JsonConvert.DeserializeObject<JObject>(responseContent);

                //验证返回数据是否正确
                if (respObj["status"].Value<string>() == "1" && respObj["key"].Value<string>() == CheckString && respObj["data"].Value<string>() == codeUrl)
                {
                    QrPath = serverUrl + respObj["path"].Value<string>();
                }
                else
                {
                    Response.Write("访问人数过多，请稍候再试");
                    Response.End();
                    return;
                }
                //QrPath = QRCodeKit.RenderQrCode(url, 400, 400);
            }
        }
    }
}